package com.stenio.fancat.service.user;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stenio.fancat.common.errorCode.ErrorCode;
import com.stenio.fancat.domain.baby.BabyPartner;
import com.stenio.fancat.domain.baby.BabyRelationship;
import com.stenio.fancat.domain.behavior.BehaviorLog;
import com.stenio.fancat.domain.user.UserPraise;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.user.UserPraiseForm;
import com.stenio.fancat.mapper.Behavior.BehaviorLogMapper;
import com.stenio.fancat.mapper.baby.BabyAccountMapper;
import com.stenio.fancat.mapper.baby.BabyPartnerMapper;
import com.stenio.fancat.mapper.baby.BabyRelationshipMapper;
import com.stenio.fancat.mapper.user.UserPraiseMapper;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.mapper.user.UserRelationshipNameMapper;
import com.stenio.fancat.util.EmptyUtil;
import com.stenio.fancat.vo.UserPraiseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * user点赞类
 */
@Service
public class UserPraiseService extends ServiceImpl<UserPraiseMapper, UserPraise> {

    @Autowired
    private UserPraiseMapper userPraiseMapper;

    @Autowired
    private BehaviorLogMapper behaviorLogMapper;

    @Autowired
    private BabyPartnerMapper babyPartnerMapper;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Autowired
    private UserRelationshipNameMapper userRelationshipNameMapper;

    @Autowired
    private BabyAccountMapper babyAccountMapper;

    @Autowired
    private BabyRelationshipMapper babyRelationshipMapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    //亲人圈的key
    @Value("${ownBehaviorList}")
    private String key;
    //伙伴圈的key
    @Value("${partnerList}")
    private String partnerListKey;
    //伙伴动态详情的key
    @Value("${partnerBehaviorList}")
    private String partnerBehaviorList;


    /**
     * 用户点赞的方法
     * @param userPraiseForm
     * @return
     * @throws FanCatException
     */
    @Transactional
    public UserPraiseVO insertPraise(UserPraiseForm userPraiseForm) throws FanCatException {
        if(EmptyUtil.isEmpty(userPraiseForm.getOperationId()) || EmptyUtil.isEmpty(userPraiseForm.getUserId()) || EmptyUtil.isEmpty(userPraiseForm.getBabyId())){
            throw new FanCatException("参数异常", ErrorCode.parameters);
        }

        //查询该用户是否对此任务点过赞
        //MP  拼接sql语句
        UserPraise userPraise = new UserPraise();
        Wrapper<UserPraise> eWrapper =
        new EntityWrapper<>(userPraise).eq("operation_id",userPraiseForm.getOperationId()).eq("user_id",userPraiseForm.getUserId());

        if(EmptyUtil.isNotEmpty(selectOne(eWrapper))){
            throw new FanCatException("用户对该任务已经点赞了",ErrorCode.alreayAddLike);
        }
        //插入数据  (点赞的操作)
        Integer m = userPraiseMapper.insertPraise(userPraiseForm.getOperationId(),userPraiseForm.getUserId(),userPraiseForm.getBabyId());

        if(m <= 0){
            throw new FanCatException("插入失败，请检查参数",ErrorCode.addLikeError);
        }

        //返回前端的数据
        UserPraiseVO userPraiseVO = new UserPraiseVO();
        //userName
        String name = userRelationshipMapper.selectUserInfoById(userPraiseForm.getUserId()).getName();
        userPraiseVO.setUserName(name);
        BabyRelationship baby = babyRelationshipMapper.selectBabyByUidAndBid(userPraiseForm.getUserId(),userPraiseForm.getBabyId());
        Integer relationship = baby.getRelationship();
        if(EmptyUtil.isNotEmpty(relationship)){
            String relationName = userRelationshipNameMapper.selectName(relationship).getRelationshipName();
            userPraiseVO.setRelationshipName(relationName);
            String babyIdSec = baby.getBabyId();
            String babyName = babyAccountMapper.selectByBid(babyIdSec).getNickName();
            userPraiseVO.setBabyName(babyName);
        }

        //操作Redis
        if(EmptyUtil.isEmpty(baby.getBabyId())){
            BehaviorLog behaviorLog = new BehaviorLog();
            behaviorLog.setOperationId(userPraiseForm.getOperationId());
            String userId = behaviorLogMapper.selectOne(behaviorLog).getUserId();
            this.operationRedis(userId,userPraiseForm.getOperationId(),userPraiseForm.getBabyId());
        }else{
            this.operationRedis(userPraiseForm.getUserId(),userPraiseForm.getOperationId(),userPraiseForm.getBabyId());
        }

        return userPraiseVO;
    }


    /**
     * 点赞操作Redis的方法
     * @param userId
     * @param operationId
     * @throws FanCatException
     */
    @Transactional
    public void operationRedis(String userId,String operationId,String babyId) throws FanCatException {
        Set<String> keys = redisTemplate.keys(babyId + "fancat" + "*");
        redisTemplate.delete(keys);
        //查询该baby关联的其他的baby
        List<BabyPartner> partners =  babyPartnerMapper.selectBabyPartnerByBid(babyId);
        //删除其他人的伙伴圈
        BehaviorLog behaviorLog = new BehaviorLog();
        behaviorLog.setOperationId(operationId);
        BehaviorLog behaviorLogNew = behaviorLogMapper.selectOne(behaviorLog);
        if (behaviorLogNew.getVisible() == 2) {
            partners.stream().forEach(partner -> {
                Set<String> keystwo = redisTemplate.keys(partner.getBabyId() + "fancat" + "*");
                redisTemplate.delete(keystwo);
            });
        }
        //删除伙伴动态详情的Redis
        BehaviorLog log = new BehaviorLog();
        log.setOperationId(operationId);
        String babyPartnerId = userRelationshipMapper.selectUserInfoById(behaviorLogMapper.selectOne(log).getUserId()).getBabyId();
        Set<String> keysSec = redisTemplate.keys(babyPartnerId+ "fancat" + "*");
        redisTemplate.delete(keysSec);

    }

}
